package top.lileix.mybatis.generator.x.generator;

import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import top.lileix.mybatis.generator.x.domain.Table;
import top.lileix.mybatis.generator.x.domain.mapper.MapperXML;
import top.lileix.mybatis.generator.x.domain.mapper.MyBatisSQL;
import top.lileix.mybatis.generator.x.domain.mapper.Result;

/**
 * mapper映射xml文件生成器
 * 
 * @author lilei
 *
 */
public class MapperXmlGenerator implements Generator {

    private String outputDir;// mapper.xml存放位置
    private String mapperPath;//
    private String domianPackPath;

    public MapperXmlGenerator(String outputDir, String mapperPath, String domianPackPath) {
	super();
	this.outputDir = outputDir;
	this.mapperPath = mapperPath;
	this.domianPackPath = domianPackPath;
    }

    @Override
    public String generatorStr(Table t) {
	MapperXML mapperXML = new MapperXML(t, domianPackPath);
	Document document = DocumentHelper.createDocument();
	document.addDocType("mapper", "-//mybatis.org//DTD Mapper 3.0//EN",
		"http://mybatis.org/dtd/mybatis-3-mapper.dtd");
	Element mapper = document.addElement("mapper");
	mapper.addAttribute("namespace", mapperPath + "." + t.getModeName() + "Mapper");
	Element resultMap = mapper.addElement("resultMap");
	resultMap.addAttribute("id", "BaseResultMap");
	resultMap.addAttribute("type", domianPackPath + "." + t.getModeName());
	resultMap.addElement("id").addAttribute("column", mapperXML.resultMap.id.column)
		.addAttribute("property", mapperXML.resultMap.id.property)
		.addAttribute("jdbcType", mapperXML.resultMap.id.jdbcType);
	for (Result r : mapperXML.resultMap.results) {
	    resultMap.addElement("result").addAttribute("column", r.column)
		    .addAttribute("property", r.property).addAttribute("jdbcType", r.jdbcType);
	}

	for (MyBatisSQL m : mapperXML.sqls) {
	    Element sql = mapper.addElement(m.sql);
	    sql.addAttribute("id", m.id);
	    if (m.parameterType != null) {
		sql.addAttribute("parameterType", m.parameterType);
	    }
	    if (m.resultMap != null) {
		sql.addAttribute("resultMap", m.resultMap);
	    }
	    sql.setText(m.text);
	}
	return document.asXML().replaceAll("&gt;", ">").replaceAll("&lt;", "<");
    }

    @Override
    public boolean generatorFile(Table t) throws IOException {
	return true;
    }

}
